package cn.tedu.straw.portal.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;
    //使用原文密码来登录
   /* @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }*/
    //使用加密密码来登录
    /*@Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }*/
    //若不使用则需要在密码前加{bcrypt}$2a$10$w3eJMFS0JvJOPh.Tgrj.4.OzimsUyUjvz3.Qxq4eMlyDtlOR1O
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    //配置请求路径对应的权限标识
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登录页面
        String loginPageUrl = "/login.html";
        //处理登录的url，即登录表单提交到哪去
        String loginProcessingUrl = "/login";
        //不需要登录即可访问URL
        String[] urls = {
                loginPageUrl,
                loginProcessingUrl,
          "/browser_components/**",
          "/css/**",
          "/img/**",
          "/js/**",
          "/npm/**",
          "/register.html",
          "/portal/user/reg/student"
        };

        //授权访问
        http.authorizeRequests()
                .antMatchers(urls).permitAll()
                .antMatchers("/test/user/add").hasAnyAuthority("创建用户","系统管理员")
                .antMatchers("/test/user/delete").hasAnyAuthority("删除用户","系统管理员")
//                .antMatchers("/test/user/update").hasAnyAuthority("/web/index","/question/upload")
                .antMatchers("/test/user/list").hasAnyAuthority("查看用户","系统管理员")
                //所有请求都是需要进行验证的
                .anyRequest().authenticated();
                http.formLogin()
                    .loginPage(loginPageUrl)
                    .loginProcessingUrl(loginProcessingUrl);
                http.csrf().disable();
    }
}
